<script lang="ts" setup>
  import { onMounted, ref, watch } from 'vue'
  import { articleColumns } from './columns'
  import { message, Modal } from 'ant-design-vue'
  import CreateArticle from './CreateArticle.vue'
  import VueMarkdown from './MarkDown.vue'
  import {
    deleteArticleReq,
    getArticleListReq,
    getKeyArticleListReq,
  } from '@/api'
  import { useKeyArticleStore } from '@/store/keyArticle'
  import { storeToRefs } from 'pinia'
  const keyArticleStore = useKeyArticleStore()
  const { keyArticle } = storeToRefs(keyArticleStore)

  import { useSearchStore } from '@/store/search'
  import usePagination from '@/hooks/usePagination'

  const searchStore = useSearchStore()
  const { searchValue } = storeToRefs(searchStore)

  const props = defineProps<{
    articleProps: {
      selectedTitle: string
      parentTitle: number
      selectedId: number
    }
    id: string
    name: string
    refreshArticleProps: any
  }>()

  // 切换表格和内容
  const isTableView = ref(true)
  const clickRecord = ref<any>(null)

  const showModal = ref(false)
  const editRecord = ref(null)

  const editArticle = (record: any) => {
    editRecord.value = record
    showModal.value = true
  }

  const deleteArticle = async (record: any) => {
    Modal.confirm({
      title: '提示',
      content: `确定删除 "${record.title}" 吗？`,
      onOk: async () => {
        const res = await deleteArticleReq({ id: record.id })
        if (res?.data) {
          message.success('文章删除成功')
          getArticleList(props.articleProps.selectedId)
        } else {
          message.error('文章删除失败')
        }
      },
    })
  }

  const articleList = ref([])

  const getArticleList = async (subCategoryId: number) => {
    const res = await getArticleListReq({ subCategoryId })
    if (res?.data) {
      articleList.value = res.data
    }
  }

  const keyArticleList = ref([])
  const getKeyArticleList = async () => {
    const res = await getKeyArticleListReq({ parentCatId: props.id })
    if (res?.data) {
      keyArticleList.value = res.data
    }
  }

  // 添加成功后更新数据
  watch(showModal, (val, oldVal) => {
    if (oldVal && !val) {
      editRecord.value = null
      getArticleList(props.articleProps.selectedId)
      getKeyArticleList()
    }
  })

  watch(
    () => props.articleProps.selectedId,
    (newVal) => {
      if (newVal) {
        clickRecord.value = null
        isTableView.value = true
        getArticleList(newVal)
      } else {
        getKeyArticleList()
      }
    },
    { immediate: true }
  )

  // 搜索文章-标题
  watch(searchValue, () => {
    if (isTableView.value) {
      if (searchValue.value) {
        if (props.articleProps.selectedId) {
          const articles = JSON.parse(JSON.stringify(articleList.value))
          articleList.value = articles.filter((item: any) =>
            item.title.includes(searchValue.value)
          )
        } else {
          const articles = JSON.parse(JSON.stringify(keyArticleList.value))
          keyArticleList.value = articles.filter((item: any) =>
            item.title.includes(searchValue.value)
          )
        }
      } else {
        if (props.articleProps.selectedId) {
          getArticleList(props.articleProps.selectedId)
        } else {
          getKeyArticleList()
        }
      }
    }
  })

  watch(
    () => keyArticle.value,
    (newVal) => {
      // @ts-ignore
      if (newVal?.id) {
        clickRecord.value = newVal
        isTableView.value = false
      }
    },
    { immediate: true }
  )

  //  点击文章标题
  const clickTitleFun = (atricle: any) => {
    clickRecord.value = atricle
    isTableView.value = false
  }

  const clickSelectTitle = () => {
    if (!isTableView.value && clickRecord.value) {
      isTableView.value = true
      clickRecord.value = null
    }
  }

  const clickNameFun = () => {
    isTableView.value = true
    clickRecord.value = null
    props.refreshArticleProps()
  }

  onMounted(() => {})

  const { pagination } = usePagination()
</script>

<template>
  <a-row class="top-row">
    <a-breadcrumb>
      <a-breadcrumb-item
        ><a
          href="javascript:void(0)"
          @click="clickNameFun"
          >{{ name }}</a
        ></a-breadcrumb-item
      >
      <a-breadcrumb-item>{{
        articleProps.parentTitle || '重点文章'
      }}</a-breadcrumb-item>
      <a-breadcrumb-item v-if="articleProps.selectedTitle">
        <a
          href="javascript:void(0)"
          @click="clickSelectTitle"
          >{{ articleProps.selectedTitle }}</a
        >
      </a-breadcrumb-item>
      <a-breadcrumb-item v-if="clickRecord && !isTableView">{{
        clickRecord.title
      }}</a-breadcrumb-item>
    </a-breadcrumb>
    <a-button
      class="headerButton"
      @click="showModal = true"
      v-if="articleProps.selectedTitle && isTableView"
      >添加文章</a-button
    >
  </a-row>
  <VueMarkdown
    v-if="!isTableView"
    :content="clickRecord?.content"
  />
  <a-table
    v-if="isTableView"
    :columns="articleColumns"
    :pagination="pagination"
    :data-source="articleProps.parentTitle ? articleList : keyArticleList"
  >
    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'operation'">
        <a
          class="tableAction"
          @click="editArticle(record)"
          style="margin-right: 10px"
          >编辑</a
        >
        <a
          class="tableAction"
          @click="deleteArticle(record)"
          >删除</a
        >
      </template>
      <template v-if="column.key === 'title'">
        <a
          class="tableAction"
          @click="clickTitleFun(record)"
          >{{ record.title }}</a
        >
      </template>
    </template>
  </a-table>

  <a-modal
    v-model:open="showModal"
    :title="editRecord ? '编辑文章' : '添加文章'"
    width="600px"
    :footer="null"
    destroyOnClose
  >
    <CreateArticle
      v-model="showModal"
      :subCategoryId="articleProps.selectedId"
      :record="editRecord"
    />
  </a-modal>
</template>

<style scoped lang="less">
  .top-row {
    margin: 16px 0;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .headerButton {
      background-color: var(--color-blue);
      color: white;
      font-size: 12px;
    }
  }
</style>
